<template>
  <div class="flex space-x-3 xl:space-x-5">
    <Avatar :url="avatar" />
    <div class="comment flex flex-col flex-wrap-reverse w-full max-w-full-calc">
      <textarea
        v-model="commentContent"
        class="w-full shadow-md rounded-md p-4 focus:outline-none input"
        id='comment-text-area'
        placeholder="我终不能改变那个开始，何必忘不了那结局"
        cols="30"
        rows="5"/>
      <div class="flex justify-between" style="text-align: right">
        <!-- 表情包开始 -->
        <Emoji @emojiUrl='handleChange'/>
        <!-- 表情包结束 -->
        <div class='sub check'>
          <!-- 极验组件 -->
<!--          <div id="captcha" :class="captchaConfig.config.product === 'bind' ? 'hideHeight' : ''">-->
<!--            <GeetestCaptcha :captcha-config="captchaConfig" />-->
<!--          </div>-->
          <button
            @click="submit"
            id="submit-button"
            class="w-32 text-white p-2 rounded-lg shadow-lg transition transform hover:scale-105 flex float-right">
            <span class="text-center flex-grow commit">发表评论</span>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent, toRefs, reactive, getCurrentInstance, computed, inject } from 'vue'
import Avatar from '@/components/Avatar.vue'
import { useUserStore } from '@/stores/user'
import { useRoute } from 'vue-router'
import { useCommentStore } from '@/stores/comment'
import { useAppStore } from '@/stores/app'
import api from '@/api/api'
import emitter from '@/utils/mitt'
import GeetestCaptcha from '@/components/GeetestCaptcha.vue'
import { ElMessage } from 'element-plus/es'
import Emoji from '@/components/Emoji/Emoji.vue'
import { emojiUtil } from '@/utils/emojiUtil'
import { Position } from '@element-plus/icons-vue'
import { useCommonStore } from '@/stores/common'

export default defineComponent({
  name: 'CommentItem',
  components: { Position, Emoji, GeetestCaptcha, Avatar },
  setup() {
    const proxy: any = getCurrentInstance()?.appContext.config.globalProperties
    const userStore = useUserStore()
    const commentStore = useCommentStore()
    const appStore = useAppStore()
    const route = useRoute()
    const commonStore = useCommonStore()
    const reactiveData = reactive({
      commentContent: '' as any,
      // captchaConfig: {
      //   config: {
      //     captchaId: inject('captchaId'),
      //     product: commonStore.isMobile ? "bind" : "float",
      //   },
      //   handler: captchaHandler,
      // },
      emojiUrl: '' as any,
      jsonArray: [] as any
    })

    const submit = () => {
      // if (reactiveData.captchaConfig.config.product === "bind") {
      //   if (window.captchaObj) {
      //     (window as any).captchaObj.showCaptcha()
      //   } else {
      //     ElMessage({
      //       message: '请等待验证初始化完成',
      //       type: 'warning'
      //     })
      //     return false
      //   }
      // } else {
        validate()
      // }
    }
    const validate = () => {
      if (userStore.userInfo === '') {
        ElMessage({
          message: '请登录后评论!',
          type: 'warning'
        })
        return
      }
      if (reactiveData.commentContent.trim() == '') {
        ElMessage({
          message: '评论不能为空!',
          type: 'warning'
        })
        return
      }
      // let result = (window as any).captchaObj.getValidate();
      // if (!result) {
      //   ElMessage({
      //     message: '请先完成验证!',
      //     type: 'warning'
      //   })
      //   return
      // }
      saveComment()
    }
    const saveComment = () => {
      const path = route.path
      const arr = path.split('/')
      emojiUtil(reactiveData.commentContent).then((value)=>{
        const params: any = {
          commentContent: value,
          type: commentStore.type
        }
        params.topicId = arr[2]
        api.saveComment(params).then(({ data }) => {
          if (data.flag) {
            fetchComments()
            let isCommentReview = appStore.websiteConfig.isCommentReview
            if (isCommentReview) {
              ElMessage({
                message: '评论成功,正在审核中!',
                type: 'warning'
              })
            } else {
              ElMessage({
                message: '评论成功!',
                type: 'success'
              })
            }
            reactiveData.commentContent = ''
          } else {
            ElMessage({
              message: data.message,
              type: 'error'
            })
          }
        })
      })
    }
    const fetchComments = () => {
      switch (commentStore.type) {
        case 1:
          emitter.emit('articleFetchComment')
          break
        case 2:
          emitter.emit('messageFetchComment')
          break
        case 3:
          emitter.emit('aboutFetchComment')
          break
        case 4:
          emitter.emit('friendLinkFetchComment')
          break
        case 5:
          emitter.emit('talkFetchComment')
      }
    }
    // function captchaHandler(captchaObj: any) {
    //   (window as any).captchaObj = captchaObj;
    //   captchaObj
    //     .appendTo("#captcha")
    //     .onReady(function () {
    //       // console.log("ready");
    //     })
    //     .onNextReady(function () {
    //       // console.log("nextReady");
    //     })
    //     .onBoxShow(function () {
    //       // console.log("boxShow");
    //     })
    //     .onError(function (e: any) {
    //       console.log(e);
    //     })
    //     .onSuccess(function () {
    //       if (reactiveData.captchaConfig.config.product === "bind") {
    //         validate()
    //       }
    //     });
    // }
    const handleChange = (value:any,name:any) => {
      reactiveData.commentContent += '['+name+']'
    }
    return {
      ...toRefs(reactiveData),
      avatar: computed(() => userStore.userInfo.avatar),
      saveComment,
      submit,
      handleChange
    }
  }
})
</script>

<style lang="scss" scoped>
.comment textarea{
  border: 0;
  margin: 0;
  vertical-align: middle;
  outline: none !important;
  width: 100%;
  accent-color: rgb(var(--color-rgb) / .8);
  background: var(--bg);
  box-shadow: var(--s-box-shadow);
  border-radius: var(--radius);
  -webkit-appearance: none;
  padding: 0.5em 1em;
  line-height: inherit;
  transition: .5s;
}
.comment-input{
  font-size: 14px;
  border: 1px solid #ebebeb;
  border-radius: 4px;
  transition: .3s border-color;
  min-height: 100px;
  max-height: 300px;
  word-break: break-word;
  padding: 10px;
  white-space: pre-wrap;
  tab-size: 4;
  word-wrap: break-word;
  line-height: 1.42;
}
.sub.check{
  margin-top: 0.5rem;
  display: inline-flex;
}

#captcha {
  height: 50px;

  &.hideHeight {
    height: 0;
  }
}
.input {
  background: var(--background-primary);
  resize: none;
}
#submit-button {
  outline: none;
  background: linear-gradient(135deg,rgb(var(--color-rgb) / .8),rgb(var(--color-sub-rgb) / .8));
  box-shadow: 0 0 1rem 0 rgb(var(--color-rgb) / .2),0 0.5rem 1rem -0.5rem rgb(var(--color-rgb) / .5);
  align-items: center;
  margin-left: 0.5rem;
  height: 100%;
}
.wire {
  border-color: var(--text-normal);
}
</style>
